package pers.sloera.leetcode.editor.cn;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 合并相似的物品
 *
 * @author sloera
 * @date 2023-02-28 23:00:20
 */
class MergeSimilarItems {
    public static void main(String[] args) {
        Solution solution = new MergeSimilarItems().new Solution();
        System.out.println(solution.mergeSimilarItems(new int[][]{{1, 1}, {4, 5}, {3, 8}}, new int[][]{{3, 1}, {1, 5}}));
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public List<List<Integer>> mergeSimilarItems(int[][] items1, int[][] items2) {
            Map<Integer, Integer> retMap = new HashMap<>(items1.length);
            for (int[] item : items1) {
                retMap.put(item[0], item[1]);
            }
            for (int[] item : items2) {
                retMap.put(item[0], retMap.getOrDefault(item[0], 0) + item[1]);
            }
            return retMap.entrySet().stream().sorted(Comparator.comparingInt(Map.Entry::getKey)).map(entry -> Arrays.asList(entry.getKey(), entry.getValue())).collect(Collectors.toList());
        }
    }
    //leetcode submit region end(Prohibit modification and deletion)

}
